package com.ssm.threadpool.config;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomNameThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public CustomNameThreadFactory(String threadName) { //构造函数中传入name作为标识
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = threadName +
                poolNumber.getAndIncrement() +
                "-thread-"; //默认的是由pool拼接，我们改为自己的name
    }

    @Override
    public Thread newThread(Runnable r) {
        // 创建相应的Thread任务
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);


        // 检查是否为守护线程
        if (t.isDaemon()) {
            // 如果是守护线程，则设置为非守护线程
            t.setDaemon(false);
        }

        // 判断线程的优先级是否为默认优先级5(可根据业务调整)
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            // 如果不是，则将该线程设置为默认优先级
            t.setPriority(Thread.NORM_PRIORITY);
        }

        return t;
    }
}
